#!/usr/bin/env python3
"""
AI日志分析引擎统一启动脚本
一键启动后端和前端服务
"""
import os
import sys
import subprocess
import time
import signal
import threading
from pathlib import Path

class AILoggingEngineStarter:
    def __init__(self):
        self.backend_process = None
        self.frontend_process = None
        self.running = True
        
    def print_banner(self):
        """打印启动横幅"""
        print("=" * 60)
        print("🚀 AI日志分析引擎 - 统一启动器")
        print("=" * 60)
        print("💾 数据持久化: 已启用")
        print("🗂️ 工作区管理: 已启用")
        print("🤖 AI智能分析: 已启用")
        print("=" * 60)
        
    def check_environment(self):
        """检查环境"""
        print("🔧 检查环境...")
        
        # 检查虚拟环境
        venv_path = Path("venv")
        if not venv_path.exists():
            print("❌ 虚拟环境不存在，请先运行: python -m venv venv")
            return False
            
        # 检查前端目录
        frontend_path = Path("frontend")
        if not frontend_path.exists():
            print("❌ 前端目录不存在")
            return False
            
        package_json = frontend_path / "package.json"
        if not package_json.exists():
            print("❌ 前端依赖配置不存在，请检查frontend目录")
            return False
            
        print("✅ 环境检查通过")
        return True
        
    def start_backend(self):
        """启动后端服务"""
        print("🔧 启动后端服务...")
        
        try:
            # Windows
            if os.name == 'nt':
                activate_cmd = r".\venv\Scripts\activate"
                python_cmd = r".\venv\Scripts\python.exe"
            else:
                # Linux/Mac
                activate_cmd = "source venv/bin/activate"
                python_cmd = "./venv/bin/python"
            
            # 启动后端
            self.backend_process = subprocess.Popen(
                [python_cmd, "run_backend.py"],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                bufsize=1,
                universal_newlines=True
            )
            
            # 等待后端启动
            print("⏳ 等待后端服务启动...")
            time.sleep(5)
            
            # 检查后端是否启动成功
            if self.backend_process.poll() is None:
                print("✅ 后端服务启动成功")
                print("📍 后端地址: http://localhost:8080")
                return True
            else:
                print("❌ 后端服务启动失败")
                stdout, stderr = self.backend_process.communicate()
                print(f"错误信息: {stderr}")
                return False
                
        except Exception as e:
            print(f"❌ 启动后端服务时出错: {e}")
            return False
            
    def start_frontend(self):
        """启动前端服务"""
        print("🔧 启动前端服务...")
        
        try:
            # 切换到前端目录
            os.chdir("frontend")
            
            # 启动前端开发服务器
            self.frontend_process = subprocess.Popen(
                ["npm", "run", "dev"],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                bufsize=1,
                universal_newlines=True
            )
            
            # 等待前端启动
            print("⏳ 等待前端服务启动...")
            time.sleep(8)
            
            # 检查前端是否启动成功
            if self.frontend_process.poll() is None:
                print("✅ 前端服务启动成功")
                print("📱 前端地址: http://localhost:5173")
                return True
            else:
                print("❌ 前端服务启动失败")
                stdout, stderr = self.frontend_process.communicate()
                print(f"错误信息: {stderr}")
                return False
                
        except Exception as e:
            print(f"❌ 启动前端服务时出错: {e}")
            return False
        finally:
            # 切回根目录
            os.chdir("..")
            
    def monitor_services(self):
        """监控服务状态"""
        def read_backend_output():
            if self.backend_process:
                for line in iter(self.backend_process.stdout.readline, ''):
                    if self.running:
                        if "ERROR" in line or "CRITICAL" in line:
                            print(f"🔴 后端: {line.strip()}")
                        elif "INFO" in line and ("启动" in line or "初始化" in line):
                            print(f"🔵 后端: {line.strip()}")
                    else:
                        break
        
        def read_frontend_output():
            if self.frontend_process:
                for line in iter(self.frontend_process.stdout.readline, ''):
                    if self.running:
                        if "error" in line.lower() or "failed" in line.lower():
                            print(f"🔴 前端: {line.strip()}")
                        elif "ready" in line.lower() or "local:" in line.lower():
                            print(f"🔵 前端: {line.strip()}")
                    else:
                        break
        
        # 启动监控线程
        if self.backend_process:
            backend_thread = threading.Thread(target=read_backend_output, daemon=True)
            backend_thread.start()
            
        if self.frontend_process:
            frontend_thread = threading.Thread(target=read_frontend_output, daemon=True)
            frontend_thread.start()
    
    def setup_signal_handlers(self):
        """设置信号处理器"""
        def signal_handler(signum, frame):
            print("\n🛑 收到停止信号，正在关闭服务...")
            self.shutdown()
            sys.exit(0)
        
        signal.signal(signal.SIGINT, signal_handler)
        if hasattr(signal, 'SIGTERM'):
            signal.signal(signal.SIGTERM, signal_handler)
    
    def shutdown(self):
        """关闭所有服务"""
        self.running = False
        
        print("🛑 正在关闭服务...")
        
        if self.frontend_process:
            print("📱 关闭前端服务...")
            self.frontend_process.terminate()
            try:
                self.frontend_process.wait(timeout=5)
                print("✅ 前端服务已关闭")
            except subprocess.TimeoutExpired:
                self.frontend_process.kill()
                print("⚠️ 强制关闭前端服务")
        
        if self.backend_process:
            print("🔧 关闭后端服务...")
            self.backend_process.terminate()
            try:
                self.backend_process.wait(timeout=5)
                print("✅ 后端服务已关闭")
            except subprocess.TimeoutExpired:
                self.backend_process.kill()
                print("⚠️ 强制关闭后端服务")
        
        print("👋 所有服务已关闭")
    
    def run(self):
        """主运行方法"""
        try:
            self.print_banner()
            
            # 检查环境
            if not self.check_environment():
                return False
            
            # 设置信号处理
            self.setup_signal_handlers()
            
            # 启动后端
            if not self.start_backend():
                return False
            
            # 启动前端
            if not self.start_frontend():
                self.shutdown()
                return False
            
            # 启动监控
            self.monitor_services()
            
            # 显示启动完成信息
            print("\n" + "=" * 60)
            print("🎉 AI日志分析引擎启动完成！")
            print("=" * 60)
            print("📍 后端服务: http://localhost:8080")
            print("📱 前端服务: http://localhost:5173")
            print("💾 数据库文件: ai_logging_engine.db")
            print("=" * 60)
            print("💡 使用说明:")
            print("   1. 访问 http://localhost:5173 开始使用")
            print("   2. 点击'工作区管理'创建或选择工作区")
            print("   3. 在工作区中创建分析会话")
            print("   4. 上传日志文件进行分析")
            print("   5. 使用AI助手进行智能问答")
            print("=" * 60)
            print("🛑 按 Ctrl+C 停止所有服务")
            print("=" * 60)
            
            # 保持运行
            while self.running:
                time.sleep(1)
                
                # 检查进程是否还在运行
                if self.backend_process and self.backend_process.poll() is not None:
                    print("❌ 后端服务意外停止")
                    break
                    
                if self.frontend_process and self.frontend_process.poll() is not None:
                    print("❌ 前端服务意外停止")
                    break
            
        except KeyboardInterrupt:
            print("\n🛑 用户中断，正在关闭服务...")
        except Exception as e:
            print(f"❌ 运行时出错: {e}")
        finally:
            self.shutdown()
        
        return True

def main():
    """主函数"""
    starter = AILoggingEngineStarter()
    success = starter.run()
    return 0 if success else 1

if __name__ == "__main__":
    sys.exit(main())
